package com.aibaixun.system.service.impl;

import cn.hutool.json.JSONUtil;
import com.aibaixun.common.constant.Constants;
import com.aibaixun.common.core.domain.R;
import com.aibaixun.common.enums.DicmDeviceTypeEnum;
import com.aibaixun.system.domain.DicmAddress;
import com.aibaixun.system.domain.DicmDevice;
import com.aibaixun.system.domain.DicmSignal;
import com.aibaixun.system.domain.dto.DicmSignalhEnergyDto;
import com.aibaixun.system.service.*;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.aibaixun.system.domain.DicmSignalh;
import com.aibaixun.system.mapper.DicmSignalhMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
* @author zhangyh
* @description 针对表【dicm_signalh(设备测点性能数据表)】的数据库操作Service实现
* @createDate 2023-09-18 17:12:00
*/
@Service
public class DicmSignalhServiceImpl extends ServiceImpl<DicmSignalhMapper, DicmSignalh>
    implements DicmSignalhService{

    @Autowired
    private DicmDeviceService dicmDeviceService;

    @Autowired
    private DicmSignalService dicmSignalService;

    @Autowired
    private RequestLogService requestLogService;

    @Autowired
    @Lazy
    private DicmAddressService dicmAddressService;

    @Override
    public R<List<DicmSignalh>> getDicmSignalhList(String deviceId) {
        List<DicmSignalh> signalhList = this.baseMapper.getDicmSignalhList(deviceId);
        return R.ok(signalhList);
    }

    @Override
    public void handleJsonData(JSONObject parseObject) {
        System.out.println("性能参数入参："+parseObject);
        String deviceId = parseObject.getString("deviceid");
        String updateTime = parseObject.getString("updatetime");
        JSONObject argsJson = JSONObject.parseObject(parseObject.getString("args"));
        DicmDevice dicmDevice = dicmDeviceService.getBaseMapper().selectOne(
            new LambdaQueryWrapper<DicmDevice>()
            .eq(DicmDevice::getDeviceId,deviceId)
        );
        if(dicmDevice == null){
            return;
        }
        List<DicmSignalh> dataList = new LinkedList<>();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        for (Map.Entry<String, Object> stringObjectEntry : argsJson.entrySet()) {
            String signalCode = stringObjectEntry.getKey();
            String dataValue = stringObjectEntry.getValue().toString();
            DicmSignal dicmSignal = dicmSignalService.getBaseMapper().selectOne(
                new LambdaQueryWrapper<DicmSignal>()
                .eq(DicmSignal::getSignalCode,signalCode)
                .eq(DicmSignal::getDeviceId,deviceId)
                .last("limit 1")
            );
            if(dicmSignal == null){
                continue;
            }
            DicmSignalh dicmSignalh = new DicmSignalh();
            dicmSignalh.setSiteId(dicmSignal.getSiteId());
            dicmSignalh.setDeviceId(dicmDevice.getDeviceId());
            dicmSignalh.setDeviceName(dicmDevice.getDeviceName());
            dicmSignalh.setDeviceType(DicmDeviceTypeEnum.getDeviceType(dicmDevice.getDeviceType()).getName());
            dicmSignalh.setSignalName(dicmSignal.getSignalName());
            dicmSignalh.setSignalId(dicmSignal.getSignalId());
            dicmSignalh.setSignalNumber(dicmSignal.getSignalNumber());
            dicmSignalh.setDataValue(dataValue);
            dicmSignalh.setDataType(Constants.INT_1);
            dicmSignalh.setUpdateTime(LocalDateTime.parse(updateTime,formatter));
            System.out.println("封装性能数据参数："+JSONUtil.parse(dicmSignalh));
            dataList.add(dicmSignalh);
        }
        System.out.println("获取性能数据:{}"+ JSONUtil.parse(dataList));
        if(dataList.size() > 0){
            this.saveBatch(dataList);
        }
    }


    @Override
    public R<Map<String, String>> getDeviceEnergyListUe(DicmSignalhEnergyDto dto) {
        Map<String, String> resultMap = new HashMap<>();

        DicmAddress address = dicmAddressService.getBaseMapper().selectOne(
            new LambdaQueryWrapper<DicmAddress>()
            .eq(DicmAddress::getUeId,dto.getAddressId())
            .last("limit 1")
        );
        if(address == null){
            return R.fail("找不到对应的ue映射关系");
        }
        if(dto.getType().intValue() == 0){
            //需要向下查询机房信息
            List<DicmAddress> addressList = dicmAddressService.getBaseMapper().selectList(
                new LambdaQueryWrapper<DicmAddress>()
                    .eq(DicmAddress::getParentId,address.getAddressId())
            );
            if(addressList.size() == 0){
                return R.fail("当前层级无可用机房信息");
            }
            dto.setAddressIds(addressList.stream().map(DicmAddress::getAddressId).collect(Collectors.toList()));
            dto.setAddressId(null);
        }else{
            dto.setAddressId(address.getAddressId());
        }

        List<DicmSignalh> dataList = this.baseMapper.getDeviceEnergyListUe(dto);

        Map<String,List<DicmSignalh>> dataMap = dataList.stream().collect(Collectors.groupingBy(DicmSignalh::getUeId));
        for (String s : dataMap.keySet()) {
            List<DicmSignalh> signalhList = dataMap.get(s);
            if(signalhList.size() > 1){
                if(dto.getType().intValue() == Constants.INT_3){
                    for (DicmSignalh dicmSignalh : signalhList) {
                        resultMap.put(dicmSignalh.getSignalNumber(),dicmSignalh.getDataValue());
                    }
                }else{
                    resultMap.put(s,calculateAverageValue(signalhList));
                }
            }else{
                resultMap.put(s,signalhList.get(0).getDataValue());
            }
        }

        return R.ok(resultMap);
    }

    @Override
    public R<List<Map<String, String>>> getDeviceEnergyList(DicmSignalhEnergyDto dto) {
        List<Map<String, String>> resultList = new LinkedList<>();
        List<DicmSignalh> dataList = this.baseMapper.getEnergyList(dto);
        Map<String,List<DicmSignalh>> dataMap = dataList.stream().collect(Collectors.groupingBy(DicmSignalh::getDeviceId));
        for (Map.Entry<String, List<DicmSignalh>> stringListEntry : dataMap.entrySet()) {
            List<DicmSignalh> signalhList = stringListEntry.getValue();
            Map<String, String> temMap = new HashMap<>();
            if(signalhList.size() > 1){
                if(dto.getType().intValue() == Constants.INT_3){
                    for (DicmSignalh dicmSignalh : signalhList) {
                        Map<String, String> temMap1 = new HashMap<>();
                        temMap1.put(dicmSignalh.getSignalNumber(),dicmSignalh.getDataValue());
                        resultList.add(temMap1);
                    }
                }else{
                    temMap.put(stringListEntry.getKey(),calculateAverageValue(signalhList));
                    resultList.add(temMap);
                }
            }else{
                temMap.put(stringListEntry.getKey(),signalhList.get(0).getDataValue());
                resultList.add(temMap);
            }
        }
        return R.ok(resultList);
    }

    @Override
    public R<List<DicmSignalh>> getDeviceSignalh(String ueId) {
        List<DicmSignalh> signalhList = this.baseMapper.getDeviceSignalh(ueId);
        return R.ok(signalhList);
    }

    @Override
    public List<DicmSignalh> queryDicmSignalhByDeviceId(String deviceId) {
        return baseMapper.queryDicmSignalhByDeviceId(deviceId);
    }

    /**
     * 计算平均值
     * @param signalhList
     * @return
     */
    public static String calculateAverageValue(List<DicmSignalh> signalhList) {
        BigDecimal sum = BigDecimal.ZERO;
        for (DicmSignalh signalh : signalhList) {
            sum = sum.add(new BigDecimal(signalh.getDataValue()));
        }
        return sum.divide(new BigDecimal(String.valueOf(signalhList.size()))).setScale(2, BigDecimal.ROUND_UP).toString();
    }

}




